/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { INCREMENTAL_INPUT_OUTPUT_CACHE } from '../../common/const/const.js';
import { hvigorCore } from '../external/core/hvigor-core.js';
import { hvigor } from '../external/core/hvigor.js';
import { CoreTaskImpl } from '../external/task/core-task-impl.js';
import { IncrementalExecTask } from '../external/task/incremental-exec-task.js';
import { IncrementalTask } from '../external/task/incremental-task.js';
import { taskProxyManager } from '../internal/task/proxy/task-proxy-manager.js';
import { HvigorLogger } from '../log/hvigor-log.js';

const log: HvigorLogger = HvigorLogger.getLogger('task-util');

/**
 * 判断任务是否是增量任务
 *
 * @param task 待判断的任务
 * @returns {boolean} 判断结果
 */
export function isIncrementalTask(task: CoreTaskImpl): boolean {
  // 是否启用 declareInputs declareInputFiles declareOutputFiles 方法缓存
  const useInputOutputCache = hvigorCore.getParameter().getProperty(INCREMENTAL_INPUT_OUTPUT_CACHE) ?? false;
  if (useInputOutputCache) {
    return task instanceof IncrementalTask;
  } else {
    if (!(task instanceof IncrementalTask)) {
      return false;
    }

    const taskInputs = task.declareInputs();
    const taskInputFiles = task.declareInputFiles();
    const taskOutputFiles = task.declareOutputFiles();
    const noInputOrOutput: boolean = taskInputs.size === 0 && taskInputFiles.collect().size === 0 && taskOutputFiles.collect().size === 0;

    if (task instanceof IncrementalExecTask) {
      return !(task.declareExecutionTool() === '' && task.declareExecutionCommand() === '' && task.declareExecutionEnv().size === 0 && noInputOrOutput);
    }

    if (noInputOrOutput) {
      log.debug(`${task.getPath()} is declared as IncrementTask, but does not implement any incremental method.`);
    }

    return !noInputOrOutput;
  }
}

/**
 * 将任务快照中的任务状态置为成功
 *
 * @param task 执行结束和成功的任务
 */
export function markTaskExecuteSuccessful(task: CoreTaskImpl): void {
  if (!task.getEnabled() || !task.taskShouldDo()) {
    return;
  }
  if (isIncrementalTask(task)) {
    taskProxyManager.getTaskProxy(task.getPath())?.getCurTaskSnapShot()?.setExecutedSuccessful();
  }
}

export function getAlignTarget(): string | undefined {
  return hvigor.getParameter().getProperty('ohos.align.target');
}
